package net.lgy.apitest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import net.lgy.apitest.model.DO.TestEnvironmentDO;
import net.lgy.apitest.mapper.TestEnvironmentMapper;
import net.lgy.apitest.service.TestEnvironmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 测试环境配置Service实现类
 */
@Service
public class TestEnvironmentServiceImpl implements TestEnvironmentService {

    @Autowired
    private TestEnvironmentMapper testEnvironmentMapper;

    @Override
    public TestEnvironmentDO getById(Long id) {
        return testEnvironmentMapper.selectById(id);
    }

    @Override
    public boolean save(TestEnvironmentDO environmentDO) {
        return testEnvironmentMapper.insert(environmentDO) > 0;
    }

    @Override
    public boolean updateById(TestEnvironmentDO environmentDO) {
        return testEnvironmentMapper.updateById(environmentDO) > 0;
    }

    @Override
    public boolean removeById(Long id) {
        return testEnvironmentMapper.deleteById(id) > 0;
    }

    @Override
    public List<TestEnvironmentDO> getByAccountNo(Long accountNo) {
        LambdaQueryWrapper<TestEnvironmentDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TestEnvironmentDO::getAccountNo, accountNo);
        return testEnvironmentMapper.selectList(queryWrapper);
    }

    @Override
    public TestEnvironmentDO getDefaultEnvironment() {
        // 这里可能需要从上下文或其他地方获取accountNo
        // 暂时返回第一个默认环境
        LambdaQueryWrapper<TestEnvironmentDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TestEnvironmentDO::getDefaultEnv, true);
        queryWrapper.last("LIMIT 1");
        return testEnvironmentMapper.selectOne(queryWrapper);
    }

    @Override
    public boolean setDefaultEnvironment(Long id, Long accountNo) {
        // 先将用户的所有环境设置为非默认
        LambdaUpdateWrapper<TestEnvironmentDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(TestEnvironmentDO::getAccountNo, accountNo);
        updateWrapper.set(TestEnvironmentDO::getDefaultEnv, false);
        testEnvironmentMapper.update(null, updateWrapper);
        
        // 然后将指定的环境设置为默认
        TestEnvironmentDO environmentDO = new TestEnvironmentDO();
        environmentDO.setId(id);
        environmentDO.setDefaultEnv(true);
        return testEnvironmentMapper.updateById(environmentDO) > 0;
    }
}